package com.hay.pay.support;

import com.hay.pay.exception.PayException;
import com.hay.pay.handler.PayConfigHandler;
import com.hay.pay.interceptor.PayInterceptor;
import com.hay.pay.model.PayConfig;
import com.hay.pay.support.ali.AliJsapiPayPlugin;
import com.hay.pay.support.wechat.merchant.WechatMerchantJsApiPayPlugin;
import com.hay.pay.support.wechat.partner.WechatPartnerJsApiPayPlugin;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 支付上下文
 * @author LiMouRen
 * @date 2024/1/24
 */
@Component
public class PayContext {

    /**
     * 支付插件存储
     */
    private static final ConcurrentHashMap<String,PayPlugin> PAY_PLUGIN_CACHE = new ConcurrentHashMap<>(16);

    /**
     * 支付拦截器
     */
    private static PayInterceptor PAY_INTERCEPTOR;

    /**
     * 支付配置处理器
     */
    private static PayConfigHandler PAY_CONFIG_HANDLER;


    /**
     * 添加插件
     */
    static {
        PAY_PLUGIN_CACHE.put(WechatMerchantJsApiPayPlugin.PAY_CHANNEL.getChannel(),new WechatMerchantJsApiPayPlugin());
        PAY_PLUGIN_CACHE.put(WechatPartnerJsApiPayPlugin.PAY_CHANNEL.getChannel(),new WechatPartnerJsApiPayPlugin());
        PAY_PLUGIN_CACHE.put(AliJsapiPayPlugin.PAY_CHANNEL.getChannel(),new AliJsapiPayPlugin());
    }

    /**
     * 获取支付插件
     * @param payChannel 支付通道号
     * @return
     */
    public static PayPlugin getPayPlugin(String payChannel) {
        PayPlugin payPlugin = PAY_PLUGIN_CACHE.get(payChannel);
        if (Objects.isNull(payPlugin)){
            throw new PayException(payChannel+"对应的支付插件不存在");
        }
        return payPlugin;
    }



    /**
     * 注册支付配置处理器
     * @param payConfigHandler 支付配置处理器
     */
    public static void registerPayConfigHandler(PayConfigHandler payConfigHandler){
        PAY_CONFIG_HANDLER = payConfigHandler;
    }

    /**
     * 注册支付拦截器
     * @param payInterceptor 支付拦截器
     */
    public static void registerPayInterceptor(PayInterceptor payInterceptor){
        PAY_INTERCEPTOR = payInterceptor;
    }

    /**
     * 获取支付拦截器
     */
    public static PayInterceptor getPayInterceptor(){
        Assert.notNull(PAY_INTERCEPTOR,"支付拦截器为空");
        return PAY_INTERCEPTOR;
    }

    public static PayConfig getPayConfig(String payChannel, String merchantCode){
        Assert.notNull(PAY_CONFIG_HANDLER,"支付配置插件为空");
        PayConfig payConfig = PAY_CONFIG_HANDLER.getPayConfig(payChannel, merchantCode);
        Assert.notNull(payConfig,"支付配置不存在");
        return payConfig;
    }

}
